﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.SilverlightMediaFramework.Player;
using SMF.HowTo.Shared.Extensions;
using SMF.HowTo.Model;
using SMF.HowTo.Data;

namespace SMF.HowTo.Player
{
    [TemplatePart(Name = VideoInfoListElementName, Type = typeof (ItemsControl))]
    public class HowToPlayer : Microsoft.SilverlightMediaFramework.Player.Player
    {
        private const string VideoInfoListElementName = "VideoInfoList";
        private const string VideoInfoSourceUrl = "http://localhost:4662/datasources/videoinfo.xml";
        private readonly Uri _videoInfoSource;
        private readonly VideoInfoDataClient _videoInfoDataClient;

        private CoreSmoothStreamingMediaElement _mediaElement;
        private ItemsControl _videoInfoList;

        public HowToPlayer()
        {
            DefaultStyleKey = typeof(HowToPlayer);
            _videoInfoSource = new Uri(VideoInfoSourceUrl);

            if (!DesignerProperties.IsInDesignTool)
            {
                _videoInfoDataClient = new VideoInfoDataClient(_videoInfoSource);
                _videoInfoDataClient.FetchCompleted += new EventHandler<Microsoft.SilverlightMediaFramework.SimpleEventArgs<IEnumerable<VideoInfo>>>(_videoInfoDataClient_FetchCompleted);
                _videoInfoDataClient.Fetch();
            }
        }

        void _videoInfoDataClient_FetchCompleted(object sender, Microsoft.SilverlightMediaFramework.SimpleEventArgs<IEnumerable<VideoInfo>> e)
        {
            IList<VideoInfo> videoInfos = e.Result.ToList();

            videoInfos.ForEach(i => i.Selected += LoadVideo);
            _videoInfoList.ItemsSource = videoInfos;
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _videoInfoList = GetTemplateChild(VideoInfoListElementName) as ItemsControl;
        }

        protected override void OnContentChanged(object oldContent, object newContent)
        {
            base.OnContentChanged(oldContent, newContent);

            _mediaElement = newContent as CoreSmoothStreamingMediaElement;
        }

        private void LoadVideo(VideoInfo selectedVideo)
        {
            _mediaElement.SmoothStreamingSource = selectedVideo.Source;
        }
    }
}